package com.googlecode.yonggemovie.widgets.imageviewer;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Insets;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.SwingConstants;

public class ImagePreviewButton extends JButton {

	private String imageId; // 图片标识
	private String imageName; // 图片名称
	private String imagePath; // 图片路径
	
    public static int SMALL_IMAGE_WIDTH = 120; // 小图片的默认宽度
    public static int SMALL_IMAGE_HEIGHT = 175; // 小图片的默认高度

	public ImagePreviewButton(ImageInfo imageInfo) {
		this.imageId = imageInfo.getId();
		this.imageName = imageInfo.getName();
		this.imagePath = imageInfo.getFilePath();

		setHorizontalTextPosition(SwingConstants.CENTER);// 在水平方向文字位于图片中央

		setVerticalTextPosition(SwingConstants.BOTTOM);// 在垂直方向文字位于图片下方

		setMargin(new Insets(0, 0, 0, 0));// 没有间距

		setContentAreaFilled(false);// 不填充内容区域

		setBorderPainted(true);// 不绘制边框

		setFocusPainted(false);// 不绘制焦点状态

		// 为按钮设置背景图片
		addComponentListener(new ComponentAdapter() {

			@Override
			public void componentResized(ComponentEvent e) {
				ImageIcon imageIcon = new ImageIcon(imagePath);// 创建ImageIcon类型的图片对象
//				int srcWidth = imageIcon.getIconWidth();
//				int srcHeight = imageIcon.getIconHeight();
//
//		        if (srcWidth <= SMALL_IMAGE_WIDTH && srcHeight <= SMALL_IMAGE_HEIGHT) {
//		        	SMALL_IMAGE_WIDTH = srcWidth;
//		        	SMALL_IMAGE_HEIGHT = srcHeight;
//		        }
//		        else {
//		        	double scale = 0;
//		        	if((double) SMALL_IMAGE_WIDTH / srcWidth > (double) SMALL_IMAGE_HEIGHT / srcHeight)
//		        		scale = (double) SMALL_IMAGE_HEIGHT / srcHeight;
//		        	else
//		        		scale =(double) SMALL_IMAGE_WIDTH / srcWidth;
//		            SMALL_IMAGE_WIDTH = (int) (srcWidth * scale);
//		            SMALL_IMAGE_HEIGHT = (int) (srcHeight * scale);
//		        }
				
//		        System.out.println(SMALL_IMAGE_WIDTH+" - "+SMALL_IMAGE_HEIGHT);
				Image image = createImage(SMALL_IMAGE_WIDTH, SMALL_IMAGE_HEIGHT);// 创建指定大小的Image类型的对象
				Graphics g = image.getGraphics();// 获得image的绘图对象

				g.drawImage(imageIcon.getImage(), 0, 0, SMALL_IMAGE_WIDTH, SMALL_IMAGE_HEIGHT,
						ImagePreviewButton.this);// 绘图图片到image

				image.flush();// 刷新image

				setIcon(new ImageIcon(image));// 设置图片

				setText(imageName);// 设置文本

				// ImageTip.set(ImagePreviewButton.this, photoV);// 设置工具提示

				setName(imageName);// 设置图片名称

				removeComponentListener(this);// 移除该监听器

			}
		});

		// 捕获鼠标事件
		addMouseListener(new MouseAdapter() {

			@Override
			public void mouseClicked(MouseEvent e) {
				if (e.getClickCount() == 1) {// 单击

				} else {// 双击

					// 比如全屏显示照片
				}
			}
		});

	}

}
